package com.sc.test.db;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import org.greenrobot.greendao.query.QueryBuilder;

import java.util.List;

/**
 * Created by Shen Chao on 2018-01-11-011 上午 10:21.
 */

public class DBManager {
    public static final String TAG = "DBManager";
    public static final String DB_NAME = "db_user";
    private volatile static DBManager mInstance;
    private DaoMaster.DevOpenHelper openHelper;
    private DaoMaster mDaoMaster;
    private DaoSession mDaoSession;
    private SQLiteDatabase db;
    private Context context;

    private DBManager(Context context) {
        this.context = context;
        openHelper = new DaoMaster.DevOpenHelper(context, DB_NAME, null);
        mDaoMaster = new DaoMaster(openHelper.getWritableDatabase());
        mDaoSession = mDaoMaster.newSession();
    }

    /**
     * 单例获取实例
     *
     * @param context
     * @return
     */
    public static DBManager getInstance(Context context) {
        if (mInstance == null) {
            synchronized (DBManager.class) {
                if (mInstance == null) {
                    mInstance = new DBManager(context);
                    return mInstance;
                }
            }
        }
        return mInstance;
    }


    /**
     * 插入数据
     *
     * @param user
     */
    public boolean add(User user) {
        boolean flag;
        UserDao userDao = mDaoSession.getUserDao();
        flag = userDao.insert(user) != -1 ? true : false;
        return flag;
    }

    /**
     * 更新数据
     *
     * @param user
     */
    public void updateUser(User user) {
        mDaoSession.getUserDao().update(user);
    }

    /**
     * 删除数据
     *
     * @param user
     */
    public void delete(User user) {
        mDaoSession.delete(user);
    }

    /**
     * 根据名称查询
     *
     * @param name
     * @return
     */
    public User findByName(String name) {
        UserDao userDao = mDaoSession.getUserDao();
        QueryBuilder<User> queryBuilder = userDao.queryBuilder();
        queryBuilder.where(UserDao.Properties.Name.eq(name));
        User u = queryBuilder.unique();
        return u;
    }

    /**
     * 查询所有数据
     *
     * @return
     */
    public List<User> findAll() {
        UserDao userDao = mDaoSession.getUserDao();
        QueryBuilder<User> queryBuilder = userDao.queryBuilder();
        List<User> userList = queryBuilder.list();
        return userList;
    }
}
